<template>
  <div class="c-wrapper">
    <!-- 左侧布局  -->
    <div class="c-content-left">
      <a-card style=" padding:30px">
        <div class="c-header h-flex">
          <p class="header-title">商户中心</p>
          <a-button type="link" @click="copyMchInfo">
            <template #icon><copy-outlined /></template>
            复制商户信息
          </a-button>
        </div>
        <div class="ite-wrapper">
          <div class="item">
            <span class="label">商户名称：</span>
            <span class="desc">{{ vdata.mchInfo.mchName }}</span>
          </div>
          <div class="item">
            <span class="label">商户简称：</span>
            <span class="desc">{{ vdata.mchInfo.mchShortName }}</span>
          </div>
          <div class="item">
            <span class="label">登录名：</span>
            <span class="desc">{{ vdata.mchInfo.loginUsername }}</span>
          </div>
          <div class="item">
            <span class="label">商户号：</span>
            <span class="desc">{{ vdata.mchInfo.mchNo }}</span>
          </div>
          <div class="item">
            <span class="label">商户类型：</span>
            <span class="desc">{{ vdata.mchInfo.type==1?'普通商户':'特约商户' }}</span>
          </div>
          <div v-if="vdata.mchInfo.type == 2" class="item">
            <span class="label">服务商号：</span>
            <span class="desc">{{ vdata.mchInfo.isvNo }}</span>
          </div>
          <!-- <div class="item">
            <span class="label">代理商号</span>
            <span class="desc">{{ vdata.mchInfo.agentNo }}</span>
          </div> -->
          <div class="item">
            <span class="label">注册时间：</span>
            <span class="desc">{{ vdata.mchInfo.createdAt }}</span>
          </div>
        </div>
        <!-- <div class="item">
            <span class="label">签约状态</span>
            <span class="desc"><a-tag color="cyan">已签约</a-tag></span>
          </div>
          <div class="item">
            <span class="label">签约到期时间</span>
            <span class="desc">{{ vdata.mchInfo.createdAt }}</span>
          </div> -->
      </a-card>
      <a-card v-if="$access('AGREEMENT_PAGE_SIGN') && vdata.isvConfigIsOpen" style="min-height: 473px;padding:30px;margin-top: 30px;">
        <div class="c-header">
          <p class="header-title">支付宝安全发管理</p>
        </div>
        <div class="s-wrapper">
          <div class="s-label">
            选择应用:
          </div>
          <div class="s-input">
            <a-select v-model:value="vdata.configAppId" class="form-item-content" placeholder="选择应用" style="width: 100%;" @change="changeAppId">
              <a-select-option v-for="(item) in vdata.mchAppList" :key="item.appId">{{ item.appName }} [{{ item.appId }}]</a-select-option>
            </a-select>
          </div>
        </div>
        <template v-if="!vdata.isAuthorize">
          <div class="zfb-null">
            <img src="@/assets/svg/zfb-pay-null.svg" alt="">
            <div class="zfb-tips">当前应用暂未开通支付宝安全发</div>
          </div>
          <div v-if="vdata.isShowButton" class="zfb-subimit-but">
            <a-button type="primary" @click="pageSign()">1>签约开通</a-button>
            <a-button type="primary" style="margin-left: 30px;" @click="queryPageSign()">2>签约查询</a-button>
          </div>
        </template>
        <template v-if="vdata.isAuthorize">
          <div class="zfb-header">
            <div class="z-h-left">
              <div class="z-h-l-title">记账本余额（元）：</div>
              <div class="z-h-l-text">{{ vdata.aliAccountBookInfo.available_amount }}</div>
            </div>
            <div class="z-h-right">
              <a-button style="margin-right: 15px;" @click="toRecharge()">前往充值</a-button>
              <a-button type="primary" @click="toTransferPage()">发起转账</a-button>
            </div>
          </div>
          <div class="ite-wrapper" style="margin-top: 30px;">
            <div class="item">
              <span class="label l-120">记账本ID：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.account_book_id }}</span>
            </div>
            <div class="item">
              <span class="label l-120">记账外卡卡号：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.ext_card_info.card_no }}</span>
            </div>
            <div class="item">
              <span class="label l-120">记账外卡户名：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.ext_card_info.bank_acc_name }}</span>
            </div>
            <div class="item">
              <span class="label l-120">记账外卡支行：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.ext_card_info.card_branch }}</span>
            </div>
            <div class="item">
              <span class="label l-120">记账外卡开户行：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.ext_card_info.card_bank }}</span>
            </div>
            <div class="item">
              <span class="label l-120">记账外卡开户地址：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.ext_card_info.card_location }}</span>
            </div>
            <div class="item">
              <span class="label l-120">记账外卡联行号：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.ext_card_info.card_deposit }}</span>
            </div>
            <div class="item">
              <span class="label l-120">记账外卡状态：</span>
              <span class="desc">{{ vdata.aliAccountBookInfo.ext_card_info.status == 'A'?'正常':'异常' }}</span>
            </div>
          </div>
        </template>
      </a-card>
    </div>
    <!-- 右侧布局 -->
    <div v-if="vdata.mchInfo.type == 2" class="c-content-right">
      <a-card style="padding:30px">
        <div class="c-header h-flex" style="margin-bottom: 40px;">
          <p class="header-title">
            支付宝代运营授权请求
          </p>
          <a-tag v-if="vdata.showAuthStatus" :color="calcZfbStatus(vdata.alipayAuthData.handleStatus,'color')" style="padding:5px 18px;">{{ calcZfbStatus(vdata.alipayAuthData.handleStatus,'text') }}</a-tag>
        </div>
        <a-alert message="注意！！！仅当使用支付宝如意lite产品时使用" type="info" style="margin-bottom: 20px;" />
        <a-form
          ref="configFormModelRef"
          :label-col="labelCol"
          labelAlign="right"
          labelWidth="120"
          :model="vdata.alipayAuthData"
          layout="horizontal"
        >
          <a-form-item label="授权方式" name="authType" :rules="[{ required: true, message: '请选择授权方式' }]">
            <a-radio-group v-model:value="vdata.alipayAuthData.authType">
              <a-radio value="qrcode">使用支付宝扫授权码</a-radio>
              <a-radio value="apply">发送支付宝授权消息</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="支付宝账号" name="alipayAccount" :rules="[{ required: true, message: '请输入支付宝账号' }]">
            <a-input v-model:value="vdata.alipayAuthData.alipayAccount" style="width: 70%;" placeholder="请输入支付宝账号(一般为手机或邮箱)" />
          </a-form-item>
          <a-form-item>
            <div class="sub-but">
              <a-button type="primary" :loading="vdata.btnLoading" @click="alipayAuthFunc"><check-circle-outlined />发起授权</a-button>
            </div>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
  <!-- 扫码授权弹窗 -->
  <a-modal v-model:visible="vdata.showAuthQrCodeUrl" title="二维码" :footer="null" :width="350" @ok="() => vdata.showAuthQrCodeUrl = false">
    <span>请使用支付宝账号【{{ vdata.alipayAuthData.alipayAccount }}】绑定的支付宝扫码，根据页面指引完成授权</span>
    <img :src="vdata.authQrCodeUrl" style="width: 300px;height: 300px;text-align: center;">
  </a-modal>

  <!-- 充值订单弹出页 -->
  <RechargeModalInfo ref="rechargeModalInfo" :callback-func="refTable" />
</template>

<script lang="ts" setup>
import RechargeModalInfo from './RechargeModal.vue' // 充值订单弹出页
import { API_ALIPAY_SP_OPERATION, reqLoad, req, $getMainUserInfo, API_URL_MCH_APP, $queryUserAgreementPageSign, $fundAccountbookQuery, $alipayAgreementPageSign } from '@/api/manage' // 接口
import { reactive, ref, getCurrentInstance, createVNode } from 'vue'
import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

const configFormModelRef = ref()
const rechargeModalInfo = ref()

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const vdata : any = reactive ({
  mchInfo: {},
  mchAppList:[],
  alipayAuthData: {}, // 支付宝代运营授权
  authQrCodeUrl: '',
  showAuthQrCodeUrl: false,
  showAuthStatus: false,
  btnLoading: false,
  aliaqfIsShow: false,  // 支付宝安全发显示开关
  configAppId: '', // 支付宝安全发选择的appid
  isAuthorize: false, // 应用授权显示
  isvConfigIsOpen: false,  // 服务商安全发是否配置
  isShowButton: false,  // 商户应用安全发是否配置
  aliAccountBookInfo: {
    ext_card_info: {} as any  // 记账外卡信息
  } as any, // 支付宝记账本详情
})
const labelCol = {
  style: { width: '150px' } 
}
$getMainUserInfo().then(res => {
  vdata.mchInfo = res
})

// 回显当前代运营授权信息
queryAuthInfo().then(res => {
  if(res) {
    vdata.alipayAuthData = res
    vdata.showAuthStatus = true
  }
})

// 查询当前授权信息
function queryAuthInfo() {
  return req.getById(API_ALIPAY_SP_OPERATION, 'authInfo')
}

// 发起支付宝代运营授权
function alipayAuthFunc() {
  queryAuthInfo().then(res => {
    if (res && res.handleStatus == 'SUCCESS') {
      /* if (res.alipayAccount == vdata.alipayAuthData.alipayAccount) {
        $infoBox.message.success('当前支付宝账号已授权通过，无需再次授权')
        return
      } */
      // 支付宝账号【' + res.alipayAccount + '】已授权成功。重新授权的同时，需要重新同步店铺，否则可能会导致无法绑定如意设备
      $infoBox.confirmDanger('授权', '确认授权？', () => {
        sendAuth()
      }, undefined, { okText: '确认授权' })
    }else {
      sendAuth()
    }
  })
}
// 支付宝代运营授权请求
function sendAuth() {
  configFormModelRef.value.validate().then(valid =>{
    if (vdata.alipayAuthData.authType == 'qrcode') {
      reqLoad.getById(API_ALIPAY_SP_OPERATION, 'queryQrcode', { alipayAccount: vdata.alipayAuthData.alipayAccount }).then(res => {
        vdata.authQrCodeUrl = decodeURIComponent(res.qrCodeUrl)
        vdata.showAuthQrCodeUrl = true
        vdata.showAuthStatus = true
      })
    }else if (vdata.alipayAuthData.authType == 'apply') {
      reqLoad.add(API_ALIPAY_SP_OPERATION + '/apply', { alipayAccount: vdata.alipayAuthData.alipayAccount }).then(res => {
        vdata.showAuthStatus = true
        $infoBox.modalSuccess('发送成功', '授权消息已发送至支付宝：' + vdata.alipayAuthData.alipayAccount + '，请前往支付宝App处理')
      })
    }
  })
}

// 查询支付宝代运营授权结果
function queryAlipayAuthResultFunc() {
  return reqLoad.getById(API_ALIPAY_SP_OPERATION, 'queryResult', undefined).then(res => {
    if (res ) {
      vdata.alipayAuthData.handleStatus =res.handleStatus
    }
  })
}
// 赋值商户信息
function copyMchInfo(){
  const copyList = [
    { title:'商户名称',value:'mchName'},
    { title:'商户简称',value:'mchShortName'},
    { title:'登录名',value:'loginUsername'},
    { title:'商户号',value:'mchNo'},
    { title:'商户类型',value:'type'},
    { title:'服务商号',value:'isvNo'},
    { title:'注册时间',value:'createdAt'},
  ]
  const copyData = copyList.map((v:any)=>{
   if(v.value =='type') return v.title +':'+ (vdata.mchInfo[v.value] == '1'?'普通商户':'特约商户')
   return v.title +':'+ vdata.mchInfo[v.value]
  }).join('\n')
  navigator && navigator.clipboard && navigator.clipboard.writeText(copyData).then(res => {
      console.log(res)
      $infoBox.message.success('复制成功！')
    }).catch(err=> {
      console.log('copy err'+err)
    })
}

// 计算授权状态
function calcZfbStatus(sta: String, key:any) {
  const staObj: any = {}
  switch (sta) {
    case 'SUCCESS':
      staObj.text = '授权成功'
      staObj.color = 'success'
      break
    case 'PROCESS':
      staObj.text = '待确认授权'
      staObj.color = 'warning'
      break
    default:
      staObj.text = '暂未授权'
      staObj.color = 'default'
      break
  }
  return staObj[key]
}

function refTable () {}

// 支付宝安全发权限
if (useUserStore().userInfo.mchType == '2' && $access('AGREEMENT_PAGE_SIGN')) {
    aliAqfConfig()
}

// 变更 appId的事件
function changeAppId (value) {
  vdata.configAppId = value
  queryUserAgreementPageSign(value)
}

// 点击充值，打开充值金额弹窗
function toRecharge () {

  if (!vdata.configAppId) {
    return $infoBox.message.console.error('请先选择应用')
  }
  rechargeModalInfo.value.show(vdata.configAppId)
}

// 跳转至转账页面
function toTransferPage () {
  router.push({
    path: '/doTransfer',
    query: { appId: vdata.configAppId, ifCode: 'aliaqfpay' }
  })
}

function aliAqfConfig() {
  // 1.查询应用
  req.list(API_URL_MCH_APP, { pageSize: -1, mchNo: vdata.mchInfo.mchNo, state: 1}).then(res2 => {
    vdata.mchAppList = res2.records
    if (vdata.mchAppList.length > 0) {
      vdata.configAppId = vdata.mchAppList[0].appId
      // 查询签约信息
      queryUserAgreementPageSign(vdata.configAppId)
    }
  })
}

function queryUserAgreementPageSign(appId) {
  // 2.查询当前应用签约详情
  $queryUserAgreementPageSign(appId).then(res => {
    // 开启显示支付宝安全发
    vdata.isvConfigIsOpen = true
    vdata.isShowButton = true
    // 如果服务商配置未配置，关闭安全发显示
    if (res.isvConfigIsOpen && res.isvConfigIsOpen == 'hide') {
      vdata.isvConfigIsOpen = false
    }
    // 如果商户应用安全发未配置，关闭安全发操作显示
    if (res.isShowButton && res.isShowButton == 'hide') {
      vdata.isShowButton = false
    }
    if (res.agreementNo && res.accountBookId) {
      // 显示当前应用已授权
      vdata.isAuthorize = true
      // 查询当前记账本信息
      $fundAccountbookQuery(appId).then(res => {
        vdata.isAuthorize = res.isAuthorize
        vdata.aliAccountBookInfo = res
      })
    }else {
      // 显示当前应用未授权开通
      vdata.isAuthorize = false
    }
  })
}

// 跳转签约页面
function pageSign() {
  $alipayAgreementPageSign(vdata.configAppId).then(res => {
    const winOpen =  window.open('', '_blank')
    winOpen?.document.write(res)
    winOpen?.focus()
  })

  Modal.warning({
    title: '注意：',
    icon: createVNode(ExclamationCircleOutlined),
    content: '请确认已完成签约',
    okText: '已签约',
    onOk() {
      return new Promise((resolve, reject) => {
        // 查询结果
        queryPageSign()
        // 关闭弹窗
        resolve(true)
      })
    },
    onCancel() {},
  })
}

// 查询签约结果
function queryPageSign() {
  $queryUserAgreementPageSign(vdata.configAppId).then(res => {
    if (!res.agreementNo || !res.accountBookId) {
      return $infoBox.message.error('请先扫码签约，再查询结果')
    }
    $infoBox.message.success('查询成功')
    // 重新查询签约信息及记账本信息
    queryUserAgreementPageSign(vdata.configAppId)
  })
}


</script>
<style lang="less" scoped>
// 布局 css 
.c-wrapper{
  display: flex;
  justify-content: space-between;
  padding-bottom: 50px;
  .c-content-left,.c-content-right{
    flex: 1%;
  }
  .c-content-left{
    margin-right: 15px;
  }
  .c-content-right{
    margin-left: 15px;
  }
}
.ite-wrapper{
  display: flex;
  flex-wrap: wrap;
  .item{
    width: 50%;
  }
}
p {
    font-size: 16px;
    font-weight: 500;
    margin:0 5px;
  }
.desc {
  font-weight: 500;
  font-size: 13px;
  letter-spacing: 0.05em;
  color: #262626;
}
.label {
  min-width: 100px;
  color: #262626ff;
  font-size: 13px;
  letter-spacing: 0.05em;
}
.l-120{
  width: 140px;
}

.item {
  display: flex;
  padding: 8px;
}

.header-title{
  color: #000000ff;
  font-weight: 600;
}
.c-header{
  margin-bottom: 15px;
}
.h-flex{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.s-wrapper{
  display: flex;
  align-items: center;
  .s-label{
    margin-left: 5px;
    
    color: #262626ff;
  }
  .s-input{
    flex: 1;
    margin-left: 150px;
  }
}
.zfb-null{
  margin: 60px  auto 30px;
  width: 218px;
  img{
    width: 218px;
    height: 97px;
  }
  .zfb-tips{
    margin-top: 24px;
    text-align: center;
    color: #b3b3b3ff;
  }
}
.zfb-subimit-but{
  display: flex;
  justify-content: center;
}
.sub-but{
  margin: 30px 150px;
}
:deep .ant-form-item-required{
  margin-right: 15px;
}
.zfb-header{
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: 30px;
  padding: 30px;
  border-top: 1px solid #F2F2F2;
  border-bottom: 1px solid #F2F2F2;
  .z-h-l-title{
    color: #262626ff;
    }
    .z-h-l-text{
      margin-top: 20px;
      color: #262626ff;
      font-size: 32px;
      font-weight: 700;
    } 
}
</style>
